<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <!-- :inline="true" - 行内表单 -->
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="keywordQuery" v-perm="'department:list'">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'department:save'">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
  <!--
    :data="departments" - 绑定的数据[]
    highlight-current-row - 当前行高亮
    v-loading="listLoading" - 加载框/忙等框
    @selection-change="selsChange" - 选项改变会触发这个函数
  -->
		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <!-- type="selection"选项 -->
      <el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="编号" width="100" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="100">
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">正常</span>
          <span style="color: red" v-else-if="scope.row.state==0">停用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)" v-perm="'department:save'">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--工具条-->
    <!--
	    :disabled="this.sels.length===0" - 当选中的条数为0就禁用
	    @click="batchRemove" - 单击事件调用batchRemove方法
    -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

    <!-- 添加或修改的对话框
      el-dialog - elementUi提供的对话框 = 模态框
    	:title="title" - 动态改变标题
    	:visible.sync="saveFormVisible"  - 模态框的显示状态
    	:close-on-click-modal="false" - 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框
      el-form - 表单
    	:model="saveForm" - 绑定表单对象
    	label-width="80px" - 标签宽度
    	:rules="saveFormRules" - 验证规则
    	ref="saveForm" - 为当前模态框取名 - 验证的时候需要用
    	prop="name" - 如果当前字段要验证，就必须写，出现*
    	auto-complete="off" - 不自动提示
    -->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <!-- saveForm.manager--获取的是每个部门经理对象 -->
          <el-select v-model="saveForm.manager" value-key="id" placeholder="请选择" clearable>
            <!--
             el-select - 下拉框
               v-model="saveForm.manager" - 回显数据
               placeholder="请选择" - 提示语
               el-option - 每一个选项
               v-for="item in managers" - 遍历
               :label="item.username" - 回显哪一个值：item对象的username属性
               :value="item" - 点击保存你要传递到后端的数据
             回显机制：
               v-model="saveForm.manager"  与 v-for中的对应
                      对应的是整个对象【id】
               :label="item.username" - 回显的时候显示哪一个：item对象的username属性
               value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
               value-key="id" - 因为我们绑定的是一个对象saveForm.manager，
                 对象里面有多个值： id: 324, username: "东邪"
               使用id作为回显的唯一标识
           -->
            <el-option v-for="item in managers"
                    :label="item.username"
                    :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 效果同上 -->
        <!--
        <el-select v-model="saveForm.manager_id" placeholder="请选择">
          <el-option v-for="item in managers"
              :label="item.username"
              :value="item.id">
            <span style="float: left">{{ item.username }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}
            </span>
          </el-option>
        </el-select>
        -->
        <el-form-item label="上级部门">
          <!--label: 'name', // 级联框显示那个属性的值
          value: 'id'    // 回显时需要,回传值的时候也需要-->
          <el-cascader v-model="saveForm.parent"
              :options="deptTree"
              :props="{ checkStrictly: true,label: 'name',value: 'id' }"
              clearable></el-cascader>
        </el-form-item>
      </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
        //分页相关的数据
        departments: [],//绑定到表格 - 显示列表数据 - 请求完成之后
			  totals: 0,//总数量 - 计算分页栏 -  请求完成之
        currentPage:1,//当前页 - 分页栏默认当前页显示
        pageSize:5,//每页显示的条数  - 计算分页栏
        listLoading: false,//表格上的加载框

        //高级查询所需数据
        keyword: '',

        //批量删除的数据
        //多条数据选中
				sels: [],//列表选中列-用于装选中的对象

        //部门经理回显所需数据
        managers: [],

        //部门树 - 无限级数
        deptTree: [],

        //修改和新增所需的数据
				saveFormVisible: false,//对话框是否显示-默认不显示
        saveLoading: false, //对话框中的加载框/忙等框
        title:'', //标题
        saveFormRules: { //验证规则
          //在失去焦点的时候 校验sn是否为空 如果为空 就会显示红色的请输入部门编号
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ],
          //在失去焦点的时候 校验name是否为空 如果为空 就会显示红色的请输入部门名称
          name: [
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ]
				},
				//新增与编辑界面数据
        saveForm: {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          manager: null,
          parent_id: null,
          parent: null
				},
			}
		},

		methods: {
      //获取部门列表
      getDepartments() {
        //传递的参数
        let para = {
          //分页参数
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          //高级查询参数 - 关键字
          keyword:this.keyword
        };
        //页面一加载就显示加载框
        this.listLoading = true;
        //NProgress.start();
        this.$http.post("/department",para).then((res) => {
          //赋值总数量
          this.totals = res.data.totals;
          //当前页的数据
          this.departments = res.data.data;
          //关闭加载框
          this.listLoading = false;
          //NProgress.done();
        }).catch( res => {
          this.$message.error("系统繁忙 请稍后再试!");
        })
      },

      //分页-点击某一页触发的方法
      handleCurrentChange(val) {
        //当前页
        this.currentPage = val;
        this.getDepartments();
      },

      //高级查询-关键字查询
      keywordQuery(){
        //关键字查询从第一页开始显示
        this.currentPage = 1;
        this.getDepartments();
      },

			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { //点击确认之后要执行的代码
          //显示加载框
          this.listLoading = true;
          //获取id
          var id = row.id;
          this.$http.delete("/department/" + id).then( res => {
            if (res.data.success){ //删除成功
              this.$message.success("删除成功");//三秒自动消失

              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.currentPage == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if (totalPage == this.currentPage && this.currentPage > 1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }

              this.getDepartments();
            }else {
              this.$message.error("删除失败");
            }
            this.listLoading = false;//关闭加载框
          }).catch( res => {
            this.$message.error("系统繁忙!请稍后再试!!!");
          })
				}).catch(() => { //点击取消之后的代码

				});
			},

      //批量删除-选项改变的时候触发
      selsChange: function (sels) {
        this.sels = sels;
      },

      //批量删除实现
      batchRemove: function () {
        //获取被选中的对象的id
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          // 开启忙等框
          this.listLoading = true;
          this.$http.patch("/department",ids).then( res => {
            if (res.data.success){
              this.$message.success("批量删除成功");
              this.currentPage = 1;
              this.getDepartments();
            }else {
             this.$message.error("批量删除失败");
            }
            // 关闭忙等框
            this.listLoading = false;
          }).catch( res => {
            this.$message.error("系统繁忙!请稍后再试!!!");
          })
        }).catch(() => {

        });
      },

			//点击添加按钮弹出对话框
			handleAdd: function () {
				this.saveForm = {
          id: null,
          sn: '',
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null,
				};
        this.title = "添加";
        //获取部门经理们
        this.getManagers();
        //获取部门树
        this.getDeptTree();
				//显示对话框
        this.saveFormVisible = true;
			},

      //点击修改按钮弹出模态框
      handleEdit: function (index, row) {
        //将row克隆给{}，再将{}赋值给editForm 防止对象引用修改的数据
        this.saveForm = Object.assign({}, row);
        this.title = "修改";
        //获取部门经理们
        this.getManagers();
        //获取部门树
        this.getDeptTree();

        //对上级部门回显的处理:{} - []
        var dirPath = this.saveForm.dirPath; //   /2/7/18/23 - [2,7,18]
        var arr = dirPath.split("/");  //["","2","7","18","23"]
        var resultArr = [];
        for(var i=1;i<arr.length-1;i++){
          resultArr[i-1] = parseInt(arr[i]); //将字符串转成整数
          //第一次：resultArr[0] = arr[1] = "2";
          //第二次：resultArr[1] = arr[2] = 7
        }
        this.saveForm.parent = resultArr;

        //显示对话框
        this.saveFormVisible = true;
      },

      //点击提交按钮新增或修改
      saveSubmit: function () {
        //所有对话框中 一个名为saveForm的对话框 验证-上面的验证规则通过了返回true 否则返回false
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let paras = Object.assign({}, this.saveForm);

              //对父部门做处理
              var parentTmp = paras.parent;// [2,7,17]  17是父部门
              if(parentTmp){
                paras.parent = null;
                paras.parent_id = parentTmp[parentTmp.length-1];
              }

              console.log(paras);
              this.$http.put("/department",paras).then( res => {
                if (res.data.success){
                  this.$message.success("操作成功");
                  this.getDepartments();
                }else {
                  this.$message.error("操作失败");
                }
                this.saveLoading = false;
                this.saveFormVisible = false;
              }).catch( res => {
                this.$message.error("系统繁忙!请稍后再试!!!");
              })
            });
          }
        });
      },

      //获取部门经理 - 所有的员工
      getManagers(){
        this.$http.get("/employee").then( res => {
          //给部门经理们赋值
          this.managers = res.data;
        })
      },

      //无限极树
      getDeptTree(){
        this.$http.get("/department/deptTree").then(res => {
          //给部门经理们赋值
          this.deptTree = res.data;
        })
      },


		},

		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>